home *** CD-ROM | disk | FTP | other *** search
- Path: tertio.co.uk!alord
- From: alord@tertio.co.uk ()
- Newsgroups: comp.lang.c,comp.unix.programmer
- Subject: Re: Q: '\n' character - strtok trick
- Date: Wed, 03 Apr 1996 14:41:14 GMT
- Organization: Personal
- Message-ID: <828542474.7672@tertio.demon.co.uk>
- References: <31616F63.481D@lava.weeg.uiowa.edu> <4jrvv3$ask@aimnet.aimnet.com> <828493319snz@genesis.demon.co.uk>
- Reply-To: Andrew_Lord@tertio.co.uk (Andrew Lord)
- NNTP-Posting-Host: tertio.demon.co.uk
- X-NNTP-Posting-Host: tertio.demon.co.uk
- X-Newsreader: slrn (0.7.6.0)
-
- In article <828493319snz@genesis.demon.co.uk>, Lawrence Kirby wrote:
- >
- >>In article <31616F63.481D@lava.weeg.uiowa.edu>,
- >>Artur Wojdat <awojdat@lava.weeg.uiowa.edu> wrote:
- >>
- >>> Is there a function or some sort of way that I could remove '\n'
- >>>charecter form the end of the string. I'm reading from two files, want to
- >>>form one line of text and then have it printed out to stdout. I use fgets to
- >>>read from the file and I noticed that it appends newline char at the end.
- >
- >There is a simple trick to remove any trailing newline character in a string
- >typically written by fgets(), say into buffer, and that is:
- >
- > strtok(buffer, "\n");
- >
- At the risk or embarassing myself infront someone who probably knows a lot more
- about the C languange than myself -
-
- Although the behaviour of strtok() is well defined I try to avoid it like the
- plague because it uses a static area to maintain state. If another function
- happens to call it between successive invocations then your screwd.
-
- Having said that, it is obvious that this example is a one-off call to strtok
- and that it is described as a 'trick'. And I have to confess that I like it!
-
- It would have to be commented though because you are using the side-effect of
- a function to achieve you primary objective? Other people (of varying ability)
- may have to maintain it.
-
- strtok(buffer,'\n'); /* Remove '\n' */
-
- Is a pleasant improvement on my old way of doing it.
- I used to use
- if ((p = strchr(buffer,'\n')) != NULL ) *p = '\0';
-
- where p is a 'char *' somewhere, but no more!
-
- Would I be correct in saying avoid using strtok to repeatedly extract tokens
- unless you can guarantee that it will NEVER be called elsewhere in the code
- between your own invocations - and such guarantees are hard to make?
-
- Andy L.
-
-
-
-